package com.nuctech.hardwaredriver.serialport_library.core.codec;

import com.nuctech.hardwaredriver.serialport_library.bean.WriteSerialPortDataBean;
import com.nuctech.hardwaredriver.util.DefaultConfigUtil;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by 心魂free on 2019/11/1.
 * <p>
 * 默认编码器
 */

public class DefaultEncoder implements SerialPortProtocolEncoder {

    @Override
    public void encode(OutputStream out, WriteSerialPortDataBean writeSerialPortDataBean) throws IOException {

        DefaultConfigUtil.receiveDataTotalLength = writeSerialPortDataBean.getReceiveDataTotalLength();

        String headCmd = writeSerialPortDataBean.getHeadCmd();
        byte[] headCmdBytes = headCmd.getBytes();
        Object obj = writeSerialPortDataBean.getT();
        if (obj != null) {

            if (obj instanceof byte[]) {

                byte[] data = (byte[]) obj;

                byte[] writeData = new byte[headCmdBytes.length + data.length];
                System.arraycopy(headCmdBytes, 0, writeData, 0, headCmdBytes.length);
                System.arraycopy(data, 0, writeData, headCmdBytes.length, data.length);

                out.write(writeData);
                out.flush();
            }

        } else {

            out.write(headCmdBytes);
            out.flush();
        }
    }
}
